package web.helper;

import java.util.ArrayList;
import java.util.List;

import javax.el.MethodExpression;
import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;

import org.apache.commons.beanutils.BeanUtils;
import org.richfaces.component.html.HtmlDropDownMenu;
import org.richfaces.component.html.HtmlMenuGroup;
import org.richfaces.component.html.HtmlMenuItem;
import org.richfaces.component.html.HtmlToolBar;

import model.bean.LabelValueBean;
import model.bean.ModuleBean;

public class WebHelper {

	public static List<SelectItem> getLabelValueConvertList(List<LabelValueBean> labelValueList) throws Exception {
    	List<SelectItem> selectItemList = new ArrayList<SelectItem>();
		SelectItem selectItem = null;

		for (LabelValueBean labelValueBean : labelValueList) {
			selectItem = new SelectItem();
			BeanUtils.copyProperties(selectItem, labelValueBean);
			selectItemList.add(selectItem);
		}
		return selectItemList;
	}

	public static HtmlToolBar getToolBarMenu(FacesContext facesContext, List<ModuleBean> moduleList) {
		HtmlToolBar htmlToolBar = new HtmlToolBar();
		HtmlDropDownMenu htmlDropDownMenu = null;
		Application application = facesContext.getApplication();
		
		
		for (ModuleBean moduleBean : moduleList) {
			htmlDropDownMenu = new HtmlDropDownMenu();
			htmlDropDownMenu.setValue(moduleBean.getModuleName());

			HtmlMenuItem htmlMenuItem = null;
			HtmlMenuGroup htmlMenuGroup = null;
			MethodExpression methodExpression = null;

			for (ModuleBean moduleItemBean : moduleBean.getModuleList()) {

				if (moduleItemBean.getModuleList().isEmpty()) {
					htmlMenuItem = new HtmlMenuItem();
					htmlMenuItem.setValue(moduleItemBean.getModuleName());

					methodExpression = (MethodExpression) application.getExpressionFactory().createMethodExpression(facesContext.getELContext(), moduleItemBean.getModuleUrl(), null, new Class<?>[0]);
					htmlMenuItem.setActionExpression(methodExpression);

					htmlDropDownMenu.getChildren().add(htmlMenuItem);
				}
				else {
					htmlMenuGroup = new HtmlMenuGroup();
					htmlMenuGroup.setValue(moduleItemBean.getModuleName());

					for (ModuleBean moduleSubItemBean : moduleItemBean.getModuleList()) {
						htmlMenuItem = new HtmlMenuItem();
						htmlMenuItem.setValue(moduleSubItemBean.getModuleName());

						methodExpression = (MethodExpression) application.getExpressionFactory().createMethodExpression(facesContext.getELContext(), moduleSubItemBean.getModuleUrl(), null, new Class<?>[0]);

						System.out.println("Valor: " + methodExpression.getExpressionString());
						htmlMenuItem.setActionExpression(methodExpression);

						htmlMenuGroup.getChildren().add(htmlMenuItem);
					}

					htmlDropDownMenu.getChildren().add(htmlMenuGroup);
				}
			}

			htmlToolBar.getChildren().add(htmlDropDownMenu);
		}
		
		return htmlToolBar;
	}
}